<script>
  import $ from '../dfish.js'
  import {
    h
  } from 'vue'
  import DropBox from './DropBox.vue'

  export default {
    name: 'w-pickbox',
    mixins: [DropBox],
    props: ['picker'],
    methods: {
      click(e) {
        if (this.$slots.default) {
          this.showDrop = !this.showDrop
          this.warn(false)
        } else if (this.x.picker) {
          this.clickPicker(e)
        }
      },
      clickClear(e) {
        e.stopPropagation()
        this.val(null)
      },
      clickPicker(e) {
        e.stopPropagation()
        let c = this.x.picker
        if (typeof c === 'function') c(this)
        else this.cmd(c, this.x.modelValue)
      },
      html_button() {
        return [
          this.isNormal && h('button', {
            class: 'w-input-bbr w-pickbox-clear f-i f-i-close',
            onclick: this.clickClear
          }),
          this.$slots.default && h('button', {
            class: 'w-input-bbr f-i f-i-caret-down',
            disabled: this.x.disabled,
          }),
          this.x.picker && h('button', {
            class: 'w-input-bbr f-i f-i-ellipsis',
            disabled: !this.isNormal,
            onclick: this.clickPicker
          })
        ]
      }
    },
    computed: {
      input_value() {
        let m = this.x.modelValue
        let f = v => v && typeof v === 'object' ? JSON.stringify(v) : v
        if (Array.isArray(m)) {
          return m.map(v => f(v && v.value)).join(',')
        } else {
          return f(m && m.value)
        }
      },
      input_text() {
        let m = this.x.modelValue
        if (Array.isArray(m)) {
          return m.map(v => v.text).join(', ')
        } else
          return m && m.text
      }
    }
  }
</script>

<style>
  .w-pickbox-clear {
    display: none;
    font-size: 16px;
  }
  .w-pickbox-clear:hover {
    color: #f00;
  }
  .w-input:hover > .w-pickbox-clear {
    display: flex;
  }
</style>